package com.zmn.oms.api.controller.third.taobao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.internal.tmc.Message;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.http.HttpUtil;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.manager.utils.SpringBeanFactoryUtil;
import com.zmn.oms.third.taobao.TaobaoTmcConstants;
import com.zmn.oms.third.taobao.TaobaoTokenManager;
import com.zmn.oms.third.taobao.TmallApiInvoker;
import com.zmn.oms.third.taobao.dto.TaobaoAccessToken;
import com.zmn.oms.third.taobao.dto.TmcComplaintUpdateDTO;
import com.zmn.oms.third.taobao.dto.api.TmallApiInvokResult;
import com.zmn.oms.third.taobao.msghandler.TmcMsgHandler;
import com.zmn.oms.third.taobao.msghandler.impl.OrderTmcMsgHandler;
import com.zmn.oms.third.taobao.service.TmallService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 类描述：
 *
 * @author LiangHailong
 * @date 2019/06/12 15:39
 */
@RestController
@RequestMapping("/taobao")
@Slf4j
public class TaobaoController {

    @Autowired
    private TmallService tmallService;

    @GetMapping("/oauth")
    public void oauth(HttpServletResponse resp) {
        try {
            String callbackUrl = TaobaoTmcConstants.REDIRECT_URL + "/taobao/callback/token";
            String url = String.format("%s?response_type=code&view=web&state=1212&client_id=%s&redirect_uri=%s",
                    TaobaoTmcConstants.AUTHORIZE_CODE_URL, TaobaoTmcConstants.APPKEY, URLEncoder.encode(callbackUrl, GlobalConsts.UTF8_ENCODING));
            resp.sendRedirect(url);
        } catch (Exception e) {
            log.error(e.getMessage(), e.getStackTrace());
        }
    }

    @GetMapping("/callback/token")
    public void getAccessTokenByCode(String code, HttpServletResponse resp) {
        String url = TaobaoTmcConstants.TOKEN_URL;
        Map<String, String> props = new HashMap();
        props.put("grant_type", "authorization_code");
        props.put("view", "web");
        props.put("client_id", TaobaoTmcConstants.APPKEY);
        props.put("client_secret", TaobaoTmcConstants.SECRET);
        props.put("redirect_uri", TaobaoTmcConstants.REDIRECT_URL);

        props.put("code", code);

        String result = null;
        try {
            /* 返回json格式:
            {
                "w1_expires_in":86400,
                "refresh_token_valid_time":1561101707969,
                "taobao_user_nick":"%E5%95%84%E6%9C%A8%E9%B8%9F%E4%BF%AE%E5%AE%B6%E7%94%B5",
                "re_expires_in":0,
                "expire_time":1561188107969,
                "token_type":"Bearer",
                "access_token":"6200828be44e28bcf39845675a2238fbe30ceg46b6609702563261712",
                "taobao_open_uid":"AAH19-C9AJMlQQbiAn-Srb1x",
                "w1_valid":1561188107969,
                "refresh_token":"6200228cb9f9f5b3b7ac548200137b1c000dfh3f16061002563261712",
                "w2_expires_in":1800,
                "w2_valid":1561103507969,
                "r1_expires_in":86400,
                "r2_expires_in":86400,
                "r2_valid":1561188107969,
                "r1_valid":1561188107969,
                "taobao_user_id":"2563261712",
                "expires_in":86400
            }
             */
            TaobaoAccessToken token = new TaobaoAccessToken();

            // 保存token
            result = HttpUtil.post(url, props);
            JSONObject jsonObject = JSON.parseObject(result);

            token.setAccessToken(jsonObject.getString("access_token"));
            token.setExpiresIn(jsonObject.getLong("expires_in"));
            token.setExpireTime(jsonObject.getLong("expire_time"));
/*
            token.setAccessToken("6201905d630d0ZZ7c9896520a671383962985ad41f9dd822563261712");
            token.setExpiresIn(31536001L);
            token.setExpireTime(1595299147103L);
*/
            TaobaoTokenManager.setToken(token);

            ServletOutputStream out = resp.getOutputStream();
            out.print(String.format("code:[%s], result:[%s]", code, result));
        } catch (Exception e) {
            log.error(e.getMessage(), e.getStackTrace());
        }
    }

    @PostMapping("/complaint/notify")
    @ResponseBody
    public ResultDTO pushComplaint(@Valid @RequestBody TmcComplaintUpdateDTO tmcComplaintUpdateDTO) {
        ResultDTO resultDTO = null;
        try {
            TmallApiInvokResult result = TmallApiInvoker.complaintUpdate(tmcComplaintUpdateDTO.getTaobaoComplaintId(),
                    tmcComplaintUpdateDTO.getRemark());
            if (result.isSuccess()) {
                resultDTO = ResultDTO.success();
            } else {
                resultDTO = ResultDTO.fail(result.getMsg());
            }
        } catch (Exception e) {
            resultDTO = ResultDTO.fail("操作失败");
        }
        return resultDTO;
    }

    @GetMapping("/order/resave")
    @ResponseBody
    public ResultDTO resaveOrder(@RequestParam Long outerId, String sign) {
        if (!"6201905d630d0ZZ7c9896520a671383962985ad41f9dd822563261712".equals(sign)) {
            return ResultDTO.fail("非法调用！");
        }

        //OrderTmcMsgHandler tmcMsgHandler = SpringBeanFactoryUtil.getBean("orderTmcMsgHandler");
        //tmcMsgHandler.saveOrderByOuterId(outerId);

        return ResultDTO.success();
    }

    @RequestMapping("/order/syncDuty")
    @ResponseBody
    public ResultDTO notifyOrder(@RequestParam Long orderId, String sign) {
        if (!"6201905d630d0ZZ7c9896520a671383962985ad41f9dd822563261712".equals(sign)) {
            return ResultDTO.fail("非法调用！");
        }

        tmallService.syncDutyTime(orderId, "手动同步");

        return ResultDTO.success();
    }

    @RequestMapping("/order/add")
    @ResponseBody
    public ResultDTO addOrder(String json, String sign) {
        if (!"6201905d630d0ZZ7c9896520a671383962985ad41f9dd822563261712".equals(sign)) {
            return ResultDTO.fail("非法调用！");
        }

        Message message = new Message();
        message.setTopic(TaobaoTmcConstants.TOPIC_FUWU_WORKCARD_INFO);
        message.setContent(json);

        OrderTmcMsgHandler tmcMsgHandler = SpringBeanFactoryUtil.getBean("orderTmcMsgHandler");
        tmcMsgHandler.procMsg(message, null);

        return ResultDTO.success();
    }

    @RequestMapping(value = "/test/order_tb", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO testOrderTb(String str) {
        Message message = new Message();
        message.setTopic(TaobaoTmcConstants.TOPIC_FUWU_WORKCARD_INFO);
        message.setContent(str);

        TmcMsgHandler tmcMsgHandler = SpringBeanFactoryUtil.getBean("orderTmcMsgHandler");
        tmcMsgHandler.procMsg(message, null);

        return ResultDTO.success();
    }

    @GetMapping("/test/complaint")
    @ResponseBody
    public ResultDTO testComplaint(@RequestParam Long id, Long taobaoOrderId, String code) {
        Message message = new Message();
        message.setTopic(TaobaoTmcConstants.TOPIC_FUWU_ANOMALY_RECOURSE);
        String str = String.format("{\"result\":{\"buyer_nick\":\"sfsfs\",\"id\":%d,\"workcard_id\":123456,\"question_type\":\"%s\",\"status\":123,\"service_order_id\":3423424,\"recourse_message_list\":[{\"recourse_text\":\"不按时预约\",\"image_urls\":[\"sfsdsdf\"],\"submit_time\":\"2016-06-26 20:19:55\"}],\"service_code\":\"灯具安装\",\"parent_biz_order_id\":%d,\"submit_time\":\"2016-06-26 20:17:48\",\"biz_order_id\":123}}",
                id, code, taobaoOrderId);
        message.setContent(str);

        //taobaoMessageHandler.onMessage(message, null);

        return ResultDTO.success();
    }

    @RequestMapping("/test/orderWarn")
    @ResponseBody
    public ResultDTO testOrderWarn(@RequestParam Long id) {
        Message message = new Message();
        message.setTopic(TaobaoTmcConstants.TOPIC_FUWU_SERVICE_MONITOR);
        String str = "{\"result\":{\"content\": \"请及时处理即将超出6小时时未回传工人信息的服务工单，详情如下：父订单编号：355750148556476416，服务子订单：355750148556476416，服务工单号：355750148556476416\", \"id\": 12345678, \"rule_id\": \"123456\", \"gmt_create\": \"123456\", \"biz_type\": 1, \"level\": 1, \"biz_id\": 523534752786357574, \"service_code\": \"灯具安装\"}}";
        message.setContent(str);

        TmcMsgHandler tmcMsgHandler = SpringBeanFactoryUtil.getBean("orderWarnTmcMsgHandler");
        tmcMsgHandler.procMsg(message, null);

        return ResultDTO.success();
    }

}
